package sgg.juc.ticket;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class MainApp {

    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

        new Thread(() -> {
            try {
                Thread.sleep(5000);      //以睡眠来模拟写入数据操作
                System.out.println("线程A写入数据完毕，等待其他线程写入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            int i = 100;
            while (i > 0) {
                i = TicketManager.sellTicket();
                if (i == 0) {
                    System.out.println("A票已售光");
                } else {
                    System.out.println("A卖到第" + i + "张票");
                }
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(5000);      //以睡眠来模拟写入数据操作
                System.out.println("线程B写入数据完毕，等待其他线程写入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            int i = 100;
            while (i > 0) {
                i = TicketManager.sellTicket();
                if (i == 0) {
                    System.out.println("B票已售光");
                } else {
                    System.out.println("B卖到第" + i + "张票");
                }
            }
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(5000);      //以睡眠来模拟写入数据操作
                System.out.println("线程C写入数据完毕，等待其他线程写入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            int i = 100;
            while (i > 0) {
                i = TicketManager.sellTicket();
                if (i == 0) {
                    System.out.println("C票已售光");
                } else {
                    System.out.println("C卖到第" + i + "张票");
                }
            }
        }).start();
    }
}
